package online.sh.cn.fy.users.servlet;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONObject;
import online.sh.cn.fy.common.api.SqlUtil;
import online.sh.cn.fy.common.utils.CompareState;
import online.sh.cn.fy.common.utils.CookieUtil;
import online.sh.cn.fy.common.utils.DES3Util;
import online.sh.cn.fy.common.utils.ResponseUtils;
import online.sh.cn.fy.common.utils.TokenUtils;
import online.sh.cn.fy.users.utils.PointsUtil;

/**
 * 签到活动
 * 详情页面
 */
@WebServlet("/getsignmonth")
public class FyUserSignServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String openid=CookieUtil.getCookieValueByName(request, "openid");
		JSONObject json=new JSONObject();
		if (null!=openid && openid!="") {
			String uuid=CookieUtil.getCookieValueByName(request, "uuid");
			if(null!=uuid && uuid.equals("0")){
				try {
					openid=DES3Util.decrypt(openid);
				} catch (Exception e) {
					log(e.getMessage());
				}
				SqlUtil tu=new SqlUtil();
				TokenUtils to=new TokenUtils();
				int today_points;
				Map user=to.getFyUserinfoMap(openid);
				String level=(String) user.get("level");
				int ex=(int) user.get("experience");
				int points=(int) user.get("points");
				Calendar cal=Calendar.getInstance();
				int year=cal.get(Calendar.YEAR);
				int month=cal.get(Calendar.MONTH)+1;
				String day=String.valueOf(cal.get(Calendar.DATE));
				if (tu.checkUser(openid, year, month)) {			//代表非首次签到用户
					Map signuser=tu.checkUserSignUp(openid, year, month);
					int today=(int)signuser.get("sign_today");
					String inrow=(String)signuser.get("sign_setday")+","+day;
					if(today==0){
						tu.updateUserSignUp(openid, inrow, year, month);
						String[] set=inrow.split(",");
						String sign_state=CompareState.getMaxState(set);
						String sign_six=String.valueOf(signuser.get("sign_six"));     //当月连续签到6天标识，0未领取，1已领取
						if(set.length<5){
							today_points=getRandom(2,99);      	//前5次签到
						}else{
							if(set.length<12){
								today_points=getRandom(11,29);  //前5次后7次签到
							}else{
								today_points=getRandom(1,9);	//剩余18次签到
							}
						}
						today_points=PointsUtil.PlusPoints(today_points, ex);
						tu.updateUserSignUpState(openid, Integer.parseInt(sign_state),today_points,today_points, year, month,0);
						to.savePointsEvent(openid, "", "每日签到", "+"+today_points);
						if(sign_six.equals("0") && sign_state.equals("6")){
							tu.updateUserSignUpState(openid, Integer.parseInt(sign_state),today_points, 100, year, month,1);
							to.savePointsEvent(openid, "", "连续6天签到", "+100");
							level=PointsUtil.CompareLevel(ex+today_points+100);
							tu.updateUserExperience(openid, today_points+100, today_points+100, level);
							json.put("six", 1);
						}else{
							level=PointsUtil.CompareLevel(ex+today_points);
							tu.updateUserExperience(openid, today_points, today_points, level);
							json.put("six", 0);
						}
						json.put("today", 0);
					}else{
						json.put("today", 1); 
					}
				}else{              	//	当月首次签到
					String elseday="";
					if (cal.get(Calendar.DATE)>1) {
						for (int i = 1; i <cal.get(Calendar.DATE); i++) {
							elseday=elseday+String.valueOf(i)+",";
						}
						elseday=elseday.substring( 0, elseday.length() -1);
					}
					today_points=getRandom(2, 99);
					today_points=PointsUtil.PlusPoints(today_points, ex);
					tu.insertSignUser(openid, 1, 1, 1, today_points, today_points, 0, month, year, day, elseday);
					to.savePointsEvent(openid, "", "每日签到", "+"+today_points);
					level=PointsUtil.CompareLevel(ex+today_points);
					tu.updateUserExperience(openid, today_points, today_points, level);
					json.put("today", 1);
					json.put("six", 0);
				}
				Map signmap=tu.checkUserSignUp(openid,year,month);
				if (null!=signmap && signmap.size()!=0) {
					String state=String.valueOf(signmap.get("sign_state"));    //连续签到数
					String set=(String)signmap.get("sign_setday");
					List date=new ArrayList();                                 //签到日期集合
					if(set.indexOf(",")!=-1){
						String[] setday=set.split(",");
						for (int i = 0; i < setday.length; i++) {
							date.add(setday[i]);
						}
						state=CompareState.getMaxState(setday);
					}else{
						date.add(set);
					}
					/*List signhelp=tu.checkUserSignHelp(openid,year,month);				  //好友帮忙补签集合
					if (null!=signhelp && signhelp.size()!=0) {
						json.put("helpsign", signhelp); 
					}else{
						json.put("helpsign", ""); 
					}*/
					json.put("result", "0");                           
					json.put("state", state); 
					json.put("setday", date); 
					json.put("todaypoints", signmap.get("today_points"));
					json.put("statepoints", signmap.get("state_points")); 
					ResponseUtils.renderJson(response, json.toString());
				}else{
					json.put("result", "1");	//没有任何签到数据
					ResponseUtils.renderJson(response, json.toString());
				}
			}else{
				json.put("result", "6");	//非认证用户
				ResponseUtils.renderJson(response, json.toString());
			}
		}else{
			json.put("result", "6");	//未检测到openid
			ResponseUtils.renderJson(response, json.toString());
		}
	}
	

	protected static void render(HttpServletResponse response, String contentType,String text) {
		response.setContentType(contentType);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//返回指定范围随机数
	public static int getRandom(int min, int max){
	    SecureRandom random = new SecureRandom();
	    int s = random.nextInt(max) % (max - min + 1) + min;
	    return s;
	}
	
	public static String changeTime(String time){
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		long ntime=new Long(time);  
		String d = format.format(ntime*1000);
		return d;
	}	
	
	public static void main(String[] args) {
		String elseday = "";
		Calendar cal=Calendar.getInstance();
		if (cal.get(Calendar.DATE)>1) {
			for (int i = 1; i <cal.get(Calendar.DATE); i++) {
				elseday=elseday+String.valueOf(i)+",";
			}
			elseday=elseday.substring( 0, elseday.length() -1);
		}
		System.out.println(elseday);
	}
}
